<?php
/**
 * This file is part of PHPlaza (http://code.google.com/p/phplaza)
 * This file is licensed under the GNU Lesser General Public License
 *      http://www.gnu.org/licenses/lgpl.html
 *
 * No warranty is given, express or implied. Use at your own risk.
 */

namespace core::components;
use core::collections as coll;

abstract class Component implements coll::ITreeItem, IHasState
{
	private $parent;
	private $children;
	private $id;
	
	public function __construct()
	{
		$this->parent = null;
		$this->children = new coll::CList();
		$this->id = '';
	}
	
	public function getParent()
	{
		return $this->parent;
	}
	
	public function setParent(coll::ITreeItem $parent)
	{
		$this->parent = $parent;
	}
	
	public function getChildren()
	{
		return $this->children;
	}
	
	public function addChild(coll::ITreeItem $child)
	{
		if ($child instanceof Component)
		{
			// find page and register component
			$parent = $this;
			while ($parent != null && !($parent instanceof core::Page))
			{
				$parent = $parent->parent;
			}
			
			if ($parent != null)
			{
				$parent->addComponent($child);
			}
		}
		
		$this->children->add($child);
		$child->setParent($this);
	}
	
	public function removeChild(coll::ITreeItem $child)
	{
		$this->children->remove($child);
		$child->setParent(null);
	}
	
	public function count()
	{
		return count($this->children);
	}
	
	public function getId()
	{
		return $this->id;
	}
	
	public function setId($id)
	{
		$this->id = $id;
	}
	
	public function __setState(State $state)
	{
		$this->id = $state->__Id;
		$this->parent = $state->__Parent;
		$this->children = $state->__Children;
		
		$this->_setState($state);
	}
	
	public function __getState()
	{
		$state = new State();
		$state->__Id = $this->id;
		$state->__Parent = $this->parent;
		$state->__Children = $this->children;
		
		$this->_getState($state);
		return $state;
	}
}